package com.baizhi.service.impl;

import com.baizhi.dao.DepartmentDao;
import com.baizhi.dao.ManagerDao;
import com.baizhi.dao.TriageDao;
import com.baizhi.entity.Department;
import com.baizhi.entity.Manager;
import com.baizhi.entity.Triage;
import com.baizhi.service.DepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private ManagerDao managerDao;
    @Autowired
    private TriageDao triageDao;
    @Override
    public int insert(Department dep) {
        return departmentDao.insert(dep);
    }

    @Override
    public int delete(Integer did) {
        List<Manager> managers = managerDao.selectByDepartmentId(did);
        List<Triage> triages = triageDao.selectByDepartment(did);
        if(managers.size()==0 && triages.size()==0){
            return departmentDao.delete(did);
        }
        return 0;
    }

    @Override
    public int deleteAny(int[] dids) {
        int result = 0;
        for (int did : dids) {
            List<Manager> managers = managerDao.selectByDepartmentId(did);
            List<Triage> triages = triageDao.selectByDepartment(did);
            if(managers.size()==0 && triages.size()==0){
                departmentDao.delete(did);
                result++;
            }
        }
        return result;
    }

    @Override
    @Transactional(readOnly = true)
    public Department selectById(Integer did) {
        Department department = departmentDao.selectById(did);
        return department;
    }

    @Override
    public int update(Department dep) {
        return departmentDao.update(dep);
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo<Department> selectByPage(Integer page,Integer limit,String name) {
        PageHelper.startPage(page,limit);
        PageInfo<Department> pageInfo = new PageInfo<>(departmentDao.selectAll(name));
        return pageInfo;
    }

    @Override
    public List<Department> selectDepartments() {
        return departmentDao.selectGetJson();
    }

    @Override
    @Transactional(readOnly = true)
    public List<Department> selectTriageStatus() {
        return departmentDao.selectTriageStatus();
    }
}
